import Request from '@/js_sdk/luch-request/request.js'
import Config from '@/config/config.js'

const http = new Request()

http.setConfig((config) => { /* 设置全局配置 */
	config.baseUrl = Config.httpServer
	config.header = {
		...config.header
	}
	return config
})

/**
 * 自定义验证器，如果返回true 则进入响应拦截器的响应成功函数(resolve)，否则进入响应拦截器的响应错误函数(reject)
 * @param { Number } statusCode - 请求响应体statusCode（只读）
 * @return { Boolean } 如果为true,则 resolve, 否则 reject
 */
http.validateStatus = (statusCode) => {
	return statusCode === 200
}

/**
 * 请求之前拦截器 
 */
http.interceptor.request((config, cancel) => { 
	const token = uni.getStorageSync('token');
	if(token){
		config.header = {
			'token':token,
			...config.header
		}
		//异步判断token是否快过期
		uni.getStorage({
			key: 'tokenTime',
			success: function (res) {
				var now = new Date().getTime();
				//token过期10000秒，距离10分钟到期就，单位毫秒
				if(now-res.data>9400000){
					//刷新token
					refreshTokenFunction()
				}
			}
		});
	}else{
		config.header = {
			...config.header
		}
	}
	return config;
});
// 是否正在刷新的标记
let isRefreshing = false
/**
 *  请求之后拦截器
 */
http.interceptor.response((response) => {
	const res = response.data;
	/**
	 * code状态码
	 * 0表示成功
	 * 3表示token错误
	 * 其他数字 表示其他错误
	 */
	if (res.code == 0) {
		return response.data;
	} else if (res.code == 3) {
		if(isRefreshing){
			return;
		}
		//刷新token
		refreshTokenFunction()
		if(isRefreshing){
			return;
		}
		response.config.header.token = uni.getStorageSync('token');
		return http.request(response.config);
	} else if (res.code == 4) {
		uni.showModal({
			title: '提示',
			content: res.message+',您可以取消继续留在该页面，或者重新登录',
			confirmText:'重新登录',
			cancelText:'取消',
			success: function(res) {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/user/login/login'
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		return response.data;
	} else {
		//提示错误信息
		uni.showToast({
			icon: 'error',
			title:res.message,
			duration:1500
		})
		return Promise.reject(response);
	}
}, (response) => {
	//提示错误信息
	console.log('response error', response);
	uni.showToast({
		icon: 'error',
		title:response.errMsg,
		duration:1500
	})
	return Promise.reject(response);
});

/**
 * 刷新token
 */
async function refreshTokenFunction(){
	if(isRefreshing){
		return;
	}
	var data = {
		refreshToken : uni.getStorageSync('refreshToken')
	};
	await http.request({
		method: 'POST',
		url: '/user/refresh',
		data: data
	}).then(res => {
		if(res.code != 0){
			//不允许重新刷新
			isRefreshing = true;
			console.log("刷新失败："+res.message);
			return;
		}
		
		let data = res.data;
		uni.setStorageSync('token',data.accessToken);
		uni.setStorageSync('tokenTime',new Date().getTime());
		uni.setStorageSync('refreshToken',data.refreshToken);
		
		//允许重新刷新
		isRefreshing = false;
	});
}

//普通请求 GET PUT POST DELETE 等等
export function request (options = {}) {
	return http.request(options);
}
//上传文件请求
export function upload (url,options = {}) {
	return http.upload(url,options);
}

export default {
	request,
	upload
}